<?php

class WidgetController extends BackOfficeController
{
    public function behaviors()
    {
        return array(
            'gotoMenu'=>array(
                'class'=>'Admin.components.GotoMenuBehavior',
            )
        );
    }
    
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>FSM::run('Cms.WidgetDefinition.get', array('id'=>$id))->model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
        $this->actionUpdate();
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate()
	{
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax','') == 'widget-definition-form');
            $result = FSM::run('Cms.WidgetDefinition.save', $_POST);
            $model = $result->model; 

            if ($this->post('ajax','') == 'widget-definition-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }   
            if (! $result->hasErrors())
            {
                $this->message = Yii::t('Core','Item has been saved successfully.');
                if ($model->id)
                    $this->redirect(array('update', 'id'=>$model->id));
                else
                    $this->refresh();
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id == 0) {
                $model = new WidgetDefinition();
            } else {
                $model = FSM::run('Cms.WidgetDefinition.get', array('id' => $id))->model;
                if (!in_array($model->container, array('cms-header','cms-footer')))
                {
                    $model->containerCustom = $model->container;
                    $model->container = 'custom';
                }
            }
        }
        
        //set items for goto menu
        $gotoMenu = $this->asa('gotoMenu');
        if (is_object($gotoMenu))
        {
            $data = array(
                array('label'=>'Pages use this widget','url'=>array('/Cms/admin/pageWidget/list', 'widget_id'=>$model->id)),
                array('label'=>'List of Instances','url'=>array('/Cms/admin/widgetData/admin', 'WidgetData[widget_id]'=>$model->id)),
                array('label'=>'List of Layouts','url'=>array('/Cms/admin/widgetLayout/admin', 'WidgetLayout[widget_id]'=>$model->id)),
            );
            $layouts = $model->layouts(array(
                'condition'=>'layouts.status=:status AND layouts.default=:default',
                'params'=>array(
                    ':status'=>true,
                    ':default'=>true,
                ))
            );
            if (count($layouts))
                $data[] = array('label'=>'Default Layout','url'=>array('/Cms/admin/widgetLayout/update', 'id'=>$layouts[0]->id));
            $data[] = array('label'=>'Create Layout','url'=>array('/Cms/admin/widgetLayout/create', 'widget_id'=>$model->id));
            $data[] = array('label'=>'Create Widget','url'=>array('/Cms/admin/widget/create'));
            $gotoMenu->data = $data;
//            Yii::trace(__CLASS__.'.'.__FUNCTION__, 'GotoMenu');
//            Yii::trace(CVarDumper::dumpAsString($gotoMenu->data), 'GotoMenu');
        }
            
        $this->render('update', array('model' => $model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            if (($id = $this->get('id',null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',',$id);
                
                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Cms.WidgetDefinition.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif(!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400,Yii::t('Core','Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400,Yii::t('Core','Invalid request. Please do not repeat this request again.'));
        }
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $this->actionAdmin();
	}

	/**
	 * Manages all models.
	 */
	/*public function actionAdmin()
	{
        $model=new WidgetDefinition('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['WidgetDefinition']))
            $model->attributes=$_GET['WidgetDefinition'];

        $this->render('admin',array(
            'model'=>$model,
        ));
	}*/
    
    public function actionStatus()
    {
        $result = FSM::run('Cms.WidgetDefinition.changeStatus', $_GET);
        echo $result->toJson();
    }
    
    /**
    * Show 'edit' screen when user clicks on a widget
    * For listing widgets, show settings. For view widget, show edit content form
    * 
    */
    public function actionUpdateInstance()
    {
        $pageWidget = PageWidget::model()->findByPk($this->get('page_widget_id',0));
        // todo: $pageWidget not found
        if (is_object($pageWidget))
        {
            $this->redirect(url($pageWidget->widget->path.'/update',$_GET));
        }
        return;
        
        $widgetId = $this->get('id', 0);
        $widgetDataId = $this->get('instanceId', 0);
        $widgetLayoutId = $this->get('widget_layout_id', 0);
        $pageWidgetId = $this->get('page_widget_id', 0);        
        
        $pagesUsed = $layouts = $attributes = $config = array();
        $widgetData = null;$container = '';
        if (Yii::app()->request->IsPostRequest)
        {
            if ($this->post('ajax','') == 'widget-data-form'){
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
            //Yii::trace('$_POST: '.CVarDumper::dumpAsString($_POST), 'UpdatePageWidget');            
            if (isset($_POST['update_page_widgets']))
            {
                $result = FSM::run('Cms.WidgetData.copy', array('id'=>$widgetDataId));
                $model = $result->model;
                $updatePageWidgets = $_POST['update_page_widgets'];
                if (strpos($updatePageWidgets, ',') !== false)
                {
                    $updatePageWidgets = explode(',', $updatePageWidgets);
                }
                else
                {
                    $updatePageWidgets = array((int) $updatePageWidgets);
                }
                //Yii::trace('$updatePageWidgets: '.CVarDumper::dumpAsString($updatePageWidgets), 'UpdatePageWidget');
                if (is_array($updatePageWidgets) && count($updatePageWidgets))
                {
                    $criteria = new CDbCriteria();
                    $criteria->addInCondition('id', $updatePageWidgets);
                    PageWidget::model()->updateAll(array('widget_data_id'=>$model->id), $criteria);
                    $_POST['WidgetData']['id'] = $model->id;
                    //Yii::trace('WidgetData_id: '.$_POST['WidgetData_id'], 'UpdatePageWidget');
                }
            }
            Yii::trace('$_POST '.CVarDumper::dumpAsString($_POST), 'WidgetData');
            $result = FSM::run('Cms.WidgetData.save', $_POST);
            
            $widgetLayoutId = $this->post('widget_layout_id', 0);
            if ($pageWidgetId && $widgetLayoutId)
            {
                //update layout
                FSM::run('Cms.pageWidget.updateLayout', array(
                    'page_widget_id'=>$pageWidgetId,
                    'widget_layout_id'=>$widgetLayoutId,
                ));
            }
            
            if (! $result->hasErrors())
            {
                if ($this->get('layout', '') == 'popup')
                {
                    echo CHtml::script("parent.window.location = parent.window.location.href.replace(/\#.*/, '');parent.\$.fancybox.close();");
                    Yii::app()->end();
                }
                else
                    $this->redirect (array('updateInstance', 'id'=>$widgetId, 'instanceId'=>$result->model->id));
            }
        }
        else
        {
            if ($pageWidgetId)
            {
                $pageWidget = PageWidget::model()->with(array('widgetData'=>array('select'=>array('id', 'widget_id'))))->findByPk($pageWidgetId);
                if (is_object($pageWidget))
                {
                    $widgetData = $pageWidget->widgetData;
                    $widgetId = $pageWidget->widgetData->widget_id;
                    $widgetLayoutId = $pageWidget->widget_layout_id;
                }
            }
            elseif ($widgetId && $widgetDataId)
            {
                $widgetData = WidgetData::model()->findByAttributes(array('widget_id'=>$widgetId, 'id'=>$widgetDataId));
                if (is_object($widgetData))
                    $widgetDataId = $widgetData->id;
            }
            
            $serviceParams = array('id' => $widgetId, 'instanceId' => $widgetDataId, 'page_widget_id'=>$pageWidgetId);
            $result = FSM::run('Cms.widget.getEditor', $serviceParams);
            $config = $result->config;
            $attributes = $result->attributes;
                       
            $pagesUsed = FSM::run('Cms.pageWidget.getPagesUsedWidgetData', array('widget_data_id'=>$widgetDataId))->pages;
        }
        
        $result = FSM::run('Cms.widgetDefinition.get', array('id'=>$widgetId));
        if ($result->hasErrors())
            throw new CHttpException('Not found widget definition.');

        $widget = $result->model;
        
        if (is_object($widgetData))
        {
            if (in_array($widgetData->type, array(WidgetDefinition::TYPE_STATIC, WidgetDefinition::TYPE_REQUIRED)))
                $container =  $widgetData->container;
        }
        elseif (in_array($widget->type, array(WidgetDefinition::TYPE_STATIC, WidgetDefinition::TYPE_REQUIRED)))
        {
            $container =  $widget->container;
        }
        
        //find all widget layouts
        $layouts = FSM::run('Cms.widgetLayout.getByType', array('type'=>$widget->type, 'widget_id'=>$widget->id))->dataProvider;
        
        $this->render('editor',array(
            'config' => $config,
            'attributes' => $attributes,
            'widget' => $widget,
            'widgetData'=> $widgetData,
            'currentLayoutId'=>$widgetLayoutId,
            'layouts'=>$layouts,
            'pagesUsed'=>$pagesUsed,
            'pageWidgetId'=>$pageWidgetId,
            'container'=>$container,
        ));
    }
    
    protected function getLayoutList($data)
    {
        $items = array();
        if (is_array($data->layouts) && count($data->layouts))
        {
            foreach ($data->layouts as $model)
            {
                array_push($items, array('label'=>$model->name, 'url'=>array('/Cms/admin/widgetLayout/update', 'id'=>$model->id), 'linkOptions'=>array('title'=>'Edit '.$model->name)));
            }
        }
        array_push($items, array('label'=>'New Layout', 'url'=>array('/Cms/admin/widgetLayout/create', 'widget_id'=>$data->id), 'linkOptions'=>array('title'=>'New Layout'), 'template'=>'[ {menu} ]'));
        return Yii::app()->controller->widget("zii.widgets.CMenu", array("items"=>$items), true);
    }
    
    /**
    * @param WidgetDefinition $data
    */
    protected function renderPageList($data)
    {
        $criteria = new CDbCriteria();
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_widget pw ON "pw".page_id = "t".id';
        $criteria->join .= "\n ".'INNER JOIN '.SITE_TABLE_PREFIX.'widget_data wdata ON "wdata".id = "pw".widget_data_id';
        $criteria->join .= "\n ".'INNER JOIN '.SITE_TABLE_PREFIX.'widget_definition wde ON "wde".id = "wdata".widget_id';
        $criteria->join .= "\n ".'INNER JOIN '.SITE_TABLE_PREFIX.'page p ON "p".id = "pw".page_id';
        $criteria->compare('"wde".id', $data->id);
        $defaultSiteId = Yii::app()->cmsManager->site['id'];
        $criteria->compare('"p".site_id', $defaultSiteId);
        $criteria->select = array('"t".title','"t".id');
        $criteria->distinct = true;
        $criteria->limit = 5;
        $pages = Page::model()->findAll($criteria);
        if (is_array($pages) && count($pages))
        {
            $items = array();
            foreach ($pages as $index => $model)
            {
                array_push($items, array('label'=>$model->title, 'url'=>array('/Cms/admin/page/update', 'id'=>$model->id), 'linkOptions'=>array('title'=>'Edit '.$model->title)));
            }
            array_push($items, array('label'=>($index == 5 ? '...' : 'View all'), 'url'=>array('/Cms/admin/pageWidget/list', 'widget_id'=>$data->id), 'linkOptions'=>array('title'=>'View all'), 'template'=>'[ {menu} ]'));
            return Yii::app()->controller->widget("zii.widgets.CMenu", array("items"=>$items), true);
        }
        return '';
    }
    
    public function actionAdmin()
    {
        $this->actionBrowse();
        /*$widgetId = Yii::app()->request->getParam('widget_id', 0);
        $tabs = array();
        $dataProvider = FSM::run('Cms.widgetLayout.getByType', array('type'=>'recent', 'widget_id'=>$widgetId))->dataProvider;
        $tabs['Recent'] = $this->renderPartial('list_content', array('type'=>'recent', 'dataProvider'=>$dataProvider), true);
        $types = WidgetDefinition::model()->getTypeOptions();
        foreach ($types as $type => $name)
        {
            $ajaxUrl = $this->createUrl('/Cms/admin/widget/type', array('type'=>$type));
            $tabs[CHtml::tag('span', array('id'=>'widget-type-'.$type), $name)] = array('ajax'=>$ajaxUrl);
        }
        //link create new widget
        $tabs['Forms'] = array('id'=>'forms','ajax'=>$this->createUrl('/Cms/admin/widget/forms'));
        $tabs['Create Widget'] = array('id'=>'create-widget','content'=>'');
        $tabs['Create Form'] = array('id'=>'create-form','content'=>'');
        
        $criteria = new CDbCriteria();
        $criteria->select = array('name', 'id');
        $criteria->order = 't.name';
        $widgets = WidgetDefinition::model()->findAll($criteria);
        $widgets = CHtml::listData($widgets, 'id', 'name');
        
        $this->render('list', array('tabs'=>$tabs, 'widgets'=>$widgets));*/
    }
    
    public function actionType($type)
    {
        $type = (int) $type;
        $widgetId = Yii::app()->request->getParam('widget_id', 0);
        $dataProvider = FSM::run('Cms.widgetLayout.getByType', array('type'=>$type, 'widget_id'=>$widgetId))->dataProvider;
        $this->renderPartial('list_content', array('type'=>$type, 'dataProvider'=>$dataProvider));
        $output = '';
        Yii::app()->clientScript->renderBodyEnd($output);
        $output = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)" \/>/', '', $output);
        $output = preg_replace('/<script type="text\/javascript" src="([^"]+)"><\/script>/', '', $output);
        echo $output;
    }
    
    public function actionInfo($widget_layout_id)
    {
        $model = WidgetLayout::model()->with('widget')->findByPk($widget_layout_id);
        
        if (!is_object($model))
            throw new CHttpException(404, 'Not found widget layout info');
        
        $this->render('info', array('model'=>$model));
    }
    
    public function actionInstancesUsedLayout($widget_layout_id)
    {
        $criteria = new CDbCriteria();
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_widget pw ON pw.widget_data_id = t.id';
        $criteria->compare('pw.widget_layout_id', $widget_layout_id);
        $criteria->distinct = true;
        $models = WidgetData::model()->findAll($criteria);
        $this->renderPartial('info_instances', array('models'=>$models));
    }
    
    public function actionPagesUsedLayout($widget_layout_id)
    {
        $widgetId = (boolean) $this->get('widget_id', 0);
        $isRequired = (boolean) $this->get('is_required', false);
        $criteria = new CDbCriteria();
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_widget pw ON pw.page_id = t.id';
        $criteria->compare('pw.widget_layout_id', $widget_layout_id);
        $criteria->distinct = true;
        $instances = Page::model()->findAll($criteria);
        if ($isRequired)
        {
            if (count($instances))
                $instances = CHtml::listData($instances, 'id', 'id');
            
            $criteria = new CDbCriteria();
            $criteria->compare('status', true);
            $criteria->order = 'title';
            $models = Page::model()->findAll($criteria);
        }
        else
        {
            $models = $instances;
            $instances = null;
        }
        $this->renderPartial('info_pages', array(
            'models'=>$models,
            'instances'=>$instances,
            'isRequired'=>$isRequired,
            'widgetId'=>$widgetId,
        ));
    }
    
    public function actionUnused()
    {
        $model=new WidgetDefinition('unused');
        $model->unsetAttributes();
        
        if(isset($_GET['WidgetDefinition']))
            $model->attributes=$_GET['WidgetDefinition'];
            
        $this->render('unused', array('model'=>$model));
    }
    
    public function actionEditForm(){
        if (Yii::app()->request->getIsPostRequest() && Yii::app()->request->getIsAjaxRequest())
        {
            Yii::app()->user->setFlash('success',1);
            // save form properties
            $result = FSM::run('Cms.Form.save', $_POST);
            echo '{ "status" : "ok", "message" : "'.$result->form_id.'" }';
            return;
        }
        
        if (Yii::app()->user->hasFlash('success'))
        {
            Yii::app()->user->getFlash('success');
            $this->message = 'Form is successfully saved.';
        }
        
        $module = $this->get('module' ,'');
        if ($module === 'system')
            $module = 'Admin';
        $contentName = $this->get('type' ,'');
        $contentName = empty($contentName) ? '' : $contentName.' Properties';
        $contentDesc = '';
        $form = Form::model()->findByPk($this->get('id',0));
        if ($form) {
            $form->permission = CPropertyValue::ensureString($form->permission);
            $elements = $form->elements;
            $contentName = $form->contentType->name;
            $contentDesc = $form->contentType->description;
            list($module,,) = explode('.', $form->contentType->model);
        } else {
            $form = new Form();
            $form->id                   = 0;
            $form->name                 = '';
            $form->table_name           = '';
            $form->description          = 'This is your form description. Click here to edit.';
            $form->redirect             = '';
            $form->success_message      = 'Success! Your submission has been saved!';
//            $form->password             = '';
//            $form->frame_height         = 0;
//            $form->unique_ip            = 0;
            $form->permission            = "";
            $form->captcha              = 0;
            $form->email              = '';
//            $form->review               = 0;     
                   
            $elements = array();
        }
        
        $elms = array();
        foreach($elements as $e) {
            $tmp = toStdObject($e);
            $tmp->lookup_type = (string) $tmp->lookup_type;
            $tmp->lookup_value = (string) $tmp->lookup_value;
            $tmp->is_db_live = 1;
            if ($tmp->type == 'file')
            {
                $tmp->file_limit = $tmp->size;
                $tmp->file_ext = $tmp->default_value;
            }
            $tmp->options = array();
            $elms[] = $tmp;
        }
        $form = toStdObject($form);
        $form->content_type_name = $contentName;
        $form->content_type_desc = $contentDesc;
        $form->module = $module;
        
        $modules = array('Site'=>'Site');
        $criteria = new CDbCriteria;
        if (isset($_GET['module'], $_GET['type']) === false || YII_DEBUG === false)
            $criteria->compare('is_system', 0);
        $criteria->order = 'name';
        $modules = Module::model()->findAll($criteria);
        if (count($modules))
        {
            $modules = CHtml::listData($modules,'name','friendly_name');
        }
        
        Yii::import('Admin.models.*');
        $criteria = new CDbCriteria;
        $criteria->order = 'name';
        $types = Vocabulary::model()->findAll($criteria);
        if (count($types))
            $types = CHtml::listData($types, 'id', 'name');
            
        $roles = array_keys(Yii::app()->authManager->roles);
        $roles = array_combine($roles, array_map('ucfirst', $roles));
        if (isset($roles[FAuthManager::ROLE_ADMINISTRATORS]))
            unset($roles[FAuthManager::ROLE_ADMINISTRATORS]);
        
        $this->render('edit_form', array(
            'form' => $form,
            'element' => $elms,
            'types' => $types,
            'modules' => $modules,
            'roles' => $roles,
        ));
    }
    
    public function actionForms()
    {
        $model=new Form('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Form']))
            $model->attributes=$_GET['Form'];
        
        $html = $this->renderPartial('form_admin',array(
            'model'=>$model,
        ), true, true);
        //don't load scripts
        $html = preg_replace('/<link rel="stylesheet" type="text\/css" href="([^"]+)\.css" \/>/', '', $html);
        $html = preg_replace('/<script type="text\/javascript" src="([^"]+)\.js"><\/script>/', '', $html);
        echo $html;
    }
    
    public function actionDeleteForm()
    {
        $id = $this->get('id', 0);
        if ($id)
        {
            $command = Yii::app()->db->createCommand();
            //delete element options
            $command->delete(SITE_TABLE_PREFIX.'form_element_option', 'form_id=:form_id', array(':form_id'=>$id));
            //delete element
            $command->reset();
            $command->delete(SITE_TABLE_PREFIX.'form_element', 'form_id=:form_id', array(':form_id'=>$id));
            //delete form
            $command->reset();
            $command->dropTable('form_'.$id);
            $command->reset();
            $command->delete(SITE_TABLE_PREFIX.'form', 'id=:id', array(':id'=>$id));
        }
    }
    
    public function actionFormExport()
    {
        $id = $this->get('id', 0);
        $form = Form::model()->findByPk($id);
        if (! is_object($form))
        {
            Yii::app()->end();
        }
        $db = Yii::app()->db;
        $tableName = 'form_'.(int) $id;
        if (($table = $db->getSchema()->getTable($tableName)) === null)
            throw new CDbException(Yii::t('yii','The table "{table}" cannot be found in the database.',
                    array('{table}'=>$tableName)));
        $columns = $table->columns;
        
        $command = $db->createCommand();
        $rows = $command->select()
            ->from($tableName)
            ->queryAll();
        
        $phpExcel = Yii::getPathOfAlias('application.vendors.phpexcel.PHPExcel');
        spl_autoload_unregister(array('YiiBase','autoload'));
        require_once($phpExcel.'.php');
        Yii::registerAutoloader(array('YiiBase','autoload'));
        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        // Set properties
        $objPHPExcel->getProperties()->setCreator("www.serta.com")
                                     ->setLastModifiedBy("www.serta.com")
                                     ->setTitle("Form Data")
                                     ->setSubject("Form Data")
                                     ->setDescription("Form Data")
                                     ->setKeywords("")
                                     ->setCategory("");

        // Add title
        $worksheet = $objPHPExcel->setActiveSheetIndex(0);
        if (is_array($columns) && count($columns))
        {
            $excelColumns = 'ABCDEFGHIJKLMNOPQRSTUWXYZ';
            $countColumn=0;
            foreach ($columns as $name => $column)
            {
                $worksheet->setCellValue($excelColumns[$countColumn++].'1', $form->generateAttributeLabel($name));
            }
            
            if (is_array($rows) && count($rows))
            {
                $countRow=2;
                foreach ($rows as $row)
                {
                    $countColumn=0;
                    foreach ($columns as $name => $column)
                    {
                        $worksheet->setCellValue($excelColumns[$countColumn++].$countRow, $row[$name]);
                    }
                    $countRow++;
                }
            }
        }
                    
        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle('Form Data');

        // Redirect output to a client’s web browser
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment;filename="form-data.csv"');
        header('Cache-Control: max-age=0');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save('php://output');
        Yii::app()->end();
    }
    
    public function actionFormData()
    {
        $id = $this->get('id', 0);
                                  
        $form = Form::model()->findByPk($id);
        $tableName = 'form_'.(int) $id;
        
        $db = Yii::app()->db;
        if (($table = $db->getSchema()->getTable($tableName)) === null)
            throw new CDbException(Yii::t('yii','The table "{table}" cannot be found in the database.',
                    array('{table}'=>$tableName)));
        $columns = array();
        if (count($table->columns))
        {
            foreach ($table->columns as $name=>$column)
            {
                $columns[] = array(
                    'header'=>$form->generateAttributeLabel($name),
                    'name'=>$name,
                    'value'=>'$data["'.$name.'"]',
                );
            }
        }
        
        $count=$db->createCommand('SELECT COUNT(*) FROM '.$tableName)->queryScalar();
        $sql='SELECT * FROM '.$tableName;
        $dataProvider=new CSqlDataProvider($sql, array(
            'totalItemCount'=>$count,
            'pagination'=>array(
                'pageSize'=>defined('Settings::PAGE_SIZE') ? Settings::PAGE_SIZE : 10,
            ),
        ));
        $this->render('form_data', array('dataProvider'=>$dataProvider, 'form'=>$form, 'columns'=>$columns));
    }
    
    public function actionBrowse()
    {        
        //Yii::app()->theme = 'new_admin';
        //$this->layout = '//layouts/box';
        $this->render('browse');        
    }
}